package com.binge.test7IO;

import cn.hutool.core.date.StopWatch;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;

/**
 * ClassName:Test7Main
 * Package:com.binge.test7
 * Description:
 *
 * @Author @Bin
 * @Date 2024/2/28-11:50
 * @Version: v1.0
 */

@Slf4j
public class Test7Main {

    volatile Run[] runs = new Run[2];

    @Test
    public void test1() throws InterruptedException {

        for (int i = 0; i < runs.length; i++) {
            runs[i] = new Run();
        }

        CountDownLatch countDownLatch = new CountDownLatch(2);

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        new Thread(() -> {
            for (long i = 0; i < 1000000000L; i++) {
                runs[0].x = i;
            }
            countDownLatch.countDown();
        }).start();

        new Thread(() -> {
            for (long i = 0; i < 1000000000L; i++) {
                runs[1].x = i;
            }
            countDownLatch.countDown();
        }).start();
        countDownLatch.await();
        stopWatch.stop();
        log.info("耗时：{}", stopWatch.getTotalTimeMillis());
    }


    private static int a = 0, b = 0;
    private static int x = 0, y = 0;

    @Test
    public void test2() throws InterruptedException {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        while (true) {
            a = b = x = y = 0;
            CountDownLatch countDownLatch = new CountDownLatch(2);
            new Thread(() -> {
                a = 1;
                x = b;
                countDownLatch.countDown();
            }).start();
            new Thread(() -> {
                b = 1;
                y = a;
                countDownLatch.countDown();
            }).start();
            countDownLatch.await();
            if (x == 0 && y == 0) {
                log.info("game over");
                break;
            }
        }
        stopWatch.stop();
        log.info("耗时：{}", stopWatch.getTotalTimeMillis());
    }
}


class Run {
    private long long1, long2, long3, long4, long5, long6, long7;
    public long x = 0;

}
